package org.uninova.mobis.api.interfaces.open.routers;

import java.io.IOException;
import java.util.ArrayList;

import org.uninova.mobis.pojos.Coordinate;
import org.uninova.mobis.utils.GISUtilsImpl;
import org.uninova.mobis.utils.HTTPUtilsImpl;

public class OSRMInterface {
	
	/**
	 * OSRMInterface class constructor
	 */
	public OSRMInterface() {}
	
	/**
	 * Gets the fastest OSRM route from the {@code origin} to the {@code destination}, and passing through the {@code waypoints}
	 * @author PAF
	 * @param origin		the coordinate of origin, in the {@link java.lang.String} format "latitude,longitude"
	 * @param destination	the coordinate of destination, in the {@link java.lang.String} format "latitude,longitude"
	 * @param waypoints		the coordinates for all waypoints, in the {@link java.lang.String} format "latitude,longitude"
	 * @return				the fastest route, in the form of a JSON {@link java.lang.String}
	 */
	public String osrmViarouteRequest(String origin, String destination, String waypoints) {
		
		String url = "" ;
		GISUtilsImpl gisUtils = new GISUtilsImpl() ;
		HTTPUtilsImpl httpUtils = new HTTPUtilsImpl() ;
		
		if (!destination.equals("") && !origin.equals("")) {
			if (waypoints == null || waypoints.equals("") ) {
				url = "http://router.project-osrm.org/viaroute?loc=" + origin + "&loc=" + destination + "&alt=true&instructions=true" ;
			}
			else {
				ArrayList<Coordinate> coords = new ArrayList<Coordinate>() ;
				ArrayList<String> waypointList = new ArrayList<String>() ;
				while (waypoints.contains("|")) {
					waypointList.add(waypoints.substring(0, waypoints.indexOf("|"))) ;
					waypoints = waypoints.substring(waypoints.indexOf("|") + 1, waypoints.length()) ;
				}
				waypointList.add(waypoints) ;
				for (int i = 0; i < waypointList.size(); i++) {
					String coordStr = waypointList.get(i) ;
					String[] latlng = coordStr.split(",") ;
					Coordinate coord = new Coordinate() ;
					coord.lat = Double.parseDouble(latlng[0]) ;
					coord.lng = Double.parseDouble(latlng[1]) ;
					coords.add(coord) ;
				}
				Coordinate originCoord = new  Coordinate(Double.parseDouble(origin.substring(0, origin.indexOf(","))), Double.parseDouble(origin.substring(origin.indexOf(",") + 1))) ;
				ArrayList<Coordinate> sorted = new ArrayList<Coordinate>() ; 
				gisUtils.sortByDistance(sorted, coords, originCoord) ;
				url = "http://router.project-osrm.org/viaroute?loc=" + origin  ;
				for (int i = 0; i < sorted.size(); i++) {
					Coordinate coord = sorted.get(i) ;
					url = url.concat("&loc=" + String.valueOf(coord.lat) + "," + String.valueOf(coord.lng)) ;
				}
				url = url.concat("&loc=" + destination + "&alt=true&instructions=true") ;
			}
			try {
				String result = httpUtils.requestURLConnection(url) ;
				return result ;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null ;
	}
}
